package com.newenergy.wisehome.ui.fragment;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.PermissionChecker;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jude.easyrecyclerview.EasyRecyclerView;
import com.newenergy.wisehome.R;
import com.newenergy.wisehome.common.MyEvent;
import com.newenergy.wisehome.common.helper.SPUtil;
import com.newenergy.wisehome.common.helper.ToastUtil;
import com.newenergy.wisehome.common.util.LocaleUtil;
import com.newenergy.wisehome.config.AppManager;
import com.newenergy.wisehome.config.Constants;
import com.newenergy.wisehome.data.bean.BallLight;
import com.newenergy.wisehome.data.bean.DeviceCategory;
import com.newenergy.wisehome.data.bean.Family;
import com.newenergy.wisehome.data.bean.SecneGroup;
import com.newenergy.wisehome.data.ormlite.dao.BallLightDao;
import com.newenergy.wisehome.data.ormlite.dao.DeviceCategoryDao;
import com.newenergy.wisehome.gateway.manager.BLLocalFamilyManager;
import com.newenergy.wisehome.services.BDService;
import com.newenergy.wisehome.services.BaiDuService;
import com.newenergy.wisehome.ui.adapter.MainGroupAdapter;
import com.newenergy.wisehome.ui.adapter.MainHEAAdapter;
import com.newenergy.wisehome.ui.widget.CustomDialog;
import com.xys.libzxing.zxing.activity.CaptureActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.weyye.hipermission.HiPermission;
import me.yokeyword.fragmentation.ISupportFragment;

/**
 *
 */
public class MainFragment extends BaseFragment {

    @BindView(R.id.btn_help)
    Button mBtnHelp;
    @BindView(R.id.tv_page)
    TextView mTvPage;
    @BindView(R.id.btn_mike)
    Button mBtnMike;
    @BindView(R.id.btn_add)
    Button mBtnAdd;
    @BindView(R.id.btn_scan)
    Button mBtnScan;
    @BindView(R.id.recyclerView_group)
    EasyRecyclerView mRecyclerViewGroup;

    @BindView(R.id.recyclerView_scene)
    EasyRecyclerView mRecyclerViewScene;

    @BindView(R.id.ll_check)
    LinearLayout mLlCheck;
    @BindView(R.id.btn_lighting)
    Button mBtnLighting;
    @BindView(R.id.btn_hea)
    Button mBtnHea;
    @BindView(R.id.btn_setup)
    Button mBtnSetup;
    @BindView(R.id.btn_add_hea)
    Button mBtnAddHea;

    @BindView(R.id.btn_on)
    Button mBtnOn;
    @BindView(R.id.btn_off)
    Button mBtnOff;
    @BindView(R.id.ll_list_main)
    RelativeLayout mLlListMain;

    @BindView(R.id.rl_hea_list)
    RelativeLayout mRlHeaList;

    private MainGroupAdapter mGroupAdapter;
    private LinearLayoutManager mGroupLayoutManager;
    private MainHEAAdapter mHEAadapter;
    private LinearLayoutManager mSceneLayoutManager;
    private Family mSelectedFamily;
    private List<SecneGroup> mSecneGroups = new ArrayList<>();
    public int mGroupIndex = 0;
    public int mHEAIndex = 0;

    private PopupWindow mPopupWindow;
    private ImageView mTipCommand;
    private int confirType = 0;//此处0代表不跳转，2代表确认的时候跳转到设置界面
    private boolean mHaveCameraPermission = false;
    private List<DeviceCategory> mGroups;
    private List<DeviceCategory> mHEAs;

    //全局定义
    private long lastClickTime = 0L;
    private int FAST_CLICK_DELAY_TIME = 1000;  // 快速点击间隔


    public MainFragment() {
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_main;
    }

    @Override
    public void init(View rootView) {
        registerEventBus();
        initGroupRecycleView();
        initSceneRecycleView();

//        initTipTextView(getContext());
        if (LocaleUtil.getLanguage().startsWith("zh")) {
            boolean isCheck = checkMike();
            mBtnMike.setSelected(isCheck);
        } else {
            mBtnMike.setVisibility(View.GONE);
            Intent intent = new Intent(mainActivity, BDService.class);
            intent.setAction("stop service");
            mainActivity.stopService(intent);
        }

    }

    private void updateGroupStatus(DeviceCategory group) {
        String groupId = group.getGroupId();
        List<DeviceCategory> groups = mGroupAdapter.getAllData();
        int i = 0;
        for (DeviceCategory group1 : groups) {
            if (group1.getGroupId().equals(groupId)) {
                AppManager.getInstance(getContext()).mGroupIndex = i;
                group1.setChecked(true);
            } else {
                group1.setChecked(false);
            }
            i++;
        }
        showGroup(true);
        mGroupAdapter.notifyDataSetChanged();

    }


    private void updateHEAStatus(DeviceCategory group) {
        String deviceId = group.getDeviceId();
        List<DeviceCategory> groups = mHEAadapter.getAllData();
        int i = 0;
        for (DeviceCategory group1 : groups) {
            if (deviceId.equals(group1.getDeviceId())) {
                AppManager.getInstance(getContext()).mHEAIndex = i;
                group1.setChecked(true);
            } else {
                group1.setChecked(false);
            }
            i++;
        }
        showGroup(false);
        mHEAadapter.notifyDataSetChanged();

    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i(TAG, "MainFragment oResume: ");
        if (AppManager.getInstance(getContext()).mCurrFamily != null) {
            mSelectedFamily = AppManager.getInstance(getContext()).mCurrFamily;
        }
        mGroupIndex = AppManager.getInstance(getContext()).mGroupIndex;
        mHEAIndex = AppManager.getInstance(getContext()).mHEAIndex;
        refreshData();
        if (mSelectedFamily != null) {
            BLLocalFamilyManager familyManager = BLLocalFamilyManager.getInstance();
            familyManager.setCurrFamily(mSelectedFamily);
            mTvPage.setText(mSelectedFamily.getName());
            DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(getContext());
            mGroups = new ArrayList<>();
            mHEAs = new ArrayList<>();
            //添加测试组（在没有隐藏的情况下）
            if (!mSelectedFamily.isHideBallLight()) {
                DeviceCategory deviceCategory = AppManager.getInstance(getContext()).mDefaultDeviceCategoryLight;
                mGroups.add(deviceCategory);
            }

            //添加默认风扇灯（在没有隐藏的情况下）
            if (!mSelectedFamily.isHideFanLamp()) {
                DeviceCategory defaultDeviceCategoryFanlamp = AppManager.getInstance(getContext()).mDefaultDeviceCategoryFanLamp;
                mHEAs.add(defaultDeviceCategoryFanlamp);
            }

            //添加默认数据风扇灯（在没有隐藏的情况下）
            if (!mSelectedFamily.isHideDataFanLamp()) {
                DeviceCategory defaultDeviceCategoryDataFanlamp = AppManager.getInstance(getContext()).mDefaultDeviceCategoryDataFanLamp;
                mHEAs.add(defaultDeviceCategoryDataFanlamp);
            }

            //添加默认风扇（在没有隐藏的情况下）
            if (!mSelectedFamily.isHideFan()) {
                DeviceCategory defaultDeviceCategoryFan = AppManager.getInstance(getContext()).mDefaultDeviceCategoryFan;
                mHEAs.add(defaultDeviceCategoryFan);
            }

            //添加默认加湿器（在没有隐藏的情况下）
            if (!mSelectedFamily.isHideHumidifier()) {
                DeviceCategory defaultDeviceCategoryHumidifier = AppManager.getInstance(getContext()).mDefaultDeviceCategoryHumidifier;
                mHEAs.add(defaultDeviceCategoryHumidifier);
            }

            //添加默认浴霸（在没有隐藏的情况下）
            if (!mSelectedFamily.isHideBathHeater()) {
                DeviceCategory defaultDeviceCategoryBathHeater = AppManager.getInstance(getContext()).mDefaultDeviceCategoryBathHeater;
                mHEAs.add(defaultDeviceCategoryBathHeater);
            }

            //临时添加一个智能开关
            DeviceCategory deviceCategory = new DeviceCategory("12345678", 11, "01", getString(R.string.default_smart_switch), "btn_smart_switch", "0B0100010000", "0B010001");
            mHEAs.add(deviceCategory);

            mGroups.addAll(deviceCategoryDao.getFamilyLighting(mSelectedFamily.getFamilyId()));
            mGroupAdapter.refreshData(mGroups);

            mHEAs.addAll(deviceCategoryDao.getFamilyHEA(mSelectedFamily.getFamilyId()));
            mHEAadapter.refreshData(mHEAs);

            if (mainActivity.isShowAllLight) {
                setCurrGroup();
            } else {
                setCurrHEA();
            }

        } else {
            mTvPage.setText(getString(R.string.no_family));
            mLlListMain.setVisibility(View.GONE);
            mGroupAdapter.refreshData(null);
            mHEAadapter.refreshData(null);
        }


        boolean b = HiPermission.checkPermission(getActivity(), Manifest.permission.CAMERA);
        if (mHaveCameraPermission) {
            if (b) {
                startActivityForResult(new Intent(getActivity(), CaptureActivity.class), 1000);
                mHaveCameraPermission = false;
            } else {
                ToastUtil.toast(getString(R.string.no_camera_permission));
            }
        }


    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (AppManager.getInstance(getContext()).mCurrFamily != null) {
                mSelectedFamily = AppManager.getInstance(getContext()).mCurrFamily;
            }
            mGroupIndex = AppManager.getInstance(getContext()).mGroupIndex;
            mHEAIndex = AppManager.getInstance(getContext()).mHEAIndex;
            refreshData();
            if (mSelectedFamily != null) {
                mTvPage.setText(mSelectedFamily.getName());
                DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(getContext());
                mGroups = new ArrayList<>();

                mHEAs = new ArrayList<>();

                //添加测试组（在没有隐藏的情况下）
                if (!mSelectedFamily.isHideBallLight()) {
//                    BallLight ballLight =new BallLight("12345678",1,"00",getString(R.string.default_device),"ce shi zu","bg_all_device_n");
                    DeviceCategory deviceCategory = AppManager.getInstance(getContext()).mDefaultDeviceCategoryLight;
                    mGroups.add(deviceCategory);
                }

                //添加默认风扇灯（在没有隐藏的情况下）
                if (!mSelectedFamily.isHideFanLamp()) {
                    DeviceCategory defaultDeviceCategoryFanlamp = AppManager.getInstance(getContext()).mDefaultDeviceCategoryFanLamp;
                    mHEAs.add(defaultDeviceCategoryFanlamp);
                }


                //添加默认数据风扇灯（在没有隐藏的情况下）
                if (!mSelectedFamily.isHideDataFanLamp()) {
                    DeviceCategory defaultDeviceCategoryDataFanlamp = AppManager.getInstance(getContext()).mDefaultDeviceCategoryDataFanLamp;
                    mHEAs.add(defaultDeviceCategoryDataFanlamp);
                }

                //添加默认风扇（在没有隐藏的情况下）
                if (!mSelectedFamily.isHideFan()) {
                    DeviceCategory defaultDeviceCategoryFan = AppManager.getInstance(getContext()).mDefaultDeviceCategoryFan;
                    mHEAs.add(defaultDeviceCategoryFan);
                }

                //添加默认加湿器（在没有隐藏的情况下）
                if (!mSelectedFamily.isHideHumidifier()) {
                    DeviceCategory defaultDeviceCategoryHumidifier = AppManager.getInstance(getContext()).mDefaultDeviceCategoryHumidifier;
                    mHEAs.add(defaultDeviceCategoryHumidifier);
                }

                //添加默认加湿器（在没有隐藏的情况下）
                if (!mSelectedFamily.isHideBathHeater()) {
                    DeviceCategory defaultDeviceCategoryBathHeater = AppManager.getInstance(getContext()).mDefaultDeviceCategoryBathHeater;
                    mHEAs.add(defaultDeviceCategoryBathHeater);
                }


                //临时添加一个智能开关
                DeviceCategory deviceCategory = new DeviceCategory("12345678", 11, "01", getString(R.string.default_smart_switch), "btn_smart_switch", "0B0100010000", "0B010001");
                mHEAs.add(deviceCategory);


                mGroups.addAll(deviceCategoryDao.getFamilyLighting(mSelectedFamily.getFamilyId()));
                mGroupAdapter.refreshData(mGroups);

                mHEAs.addAll(deviceCategoryDao.getFamilyHEA(mSelectedFamily.getFamilyId()));
                mHEAadapter.refreshData(mHEAs);

                if (mainActivity.isShowAllLight) {
                    setCurrGroup();
                } else {
                    setCurrHEA();
                }

            } else {
                mTvPage.setText(getString(R.string.no_family));
                mLlListMain.setVisibility(View.GONE);
                mGroupAdapter.refreshData(null);
                mHEAadapter.refreshData(null);
            }


            boolean b = HiPermission.checkPermission(getActivity(), Manifest.permission.CAMERA);
            if (mHaveCameraPermission) {
                if (b) {
                    startActivityForResult(new Intent(getActivity(), CaptureActivity.class), 1000);
                    mHaveCameraPermission = false;
                } else {
                    ToastUtil.toast(getString(R.string.no_camera_permission));
                }
            }

            boolean isCheck = checkMike();
            mBtnMike.setSelected(isCheck);
        }
    }

    private void setCurrGroup() {
        List<DeviceCategory> groups = mGroupAdapter.getAllData();
        if (groups == null || groups.size() < 1) {
            AppManager.getInstance(getContext()).mSelectDeviceCategory = null;
            return;
        } else {
            for (DeviceCategory group : groups) {
                group.setChecked(false);
            }
            if (mGroupIndex < 0 || mGroupIndex >= groups.size()) mGroupIndex = 0;
            DeviceCategory group = groups.get(mGroupIndex);
            group.setChecked(true);

            if (mainActivity.isShowAllLight) {
                AppManager.getInstance(getContext()).mSelectDeviceCategory = group;

                if (group.getFamilyId().equalsIgnoreCase("12345678")) {
                    AppManager.getInstance(getContext()).selectGroup = AppManager.getInstance(getContext()).mDefaultBallLight;
                } else {
                    BallLightDao ballLightDao = new BallLightDao(getContext());
                    AppManager.getInstance(getContext()).selectGroup = ballLightDao.getByUuid(group.getUuid());
                }

            }

            mGroupAdapter.notifyDataSetChanged();
        }
    }


    private void setCurrHEA() {
        List<DeviceCategory> mHEAs = mHEAadapter.getAllData();
        if (mHEAs == null || mHEAs.size() < 1) {
            return;
        } else {
            for (DeviceCategory hea : mHEAs) {
                hea.setChecked(false);
            }
            if (mHEAIndex < 0 || mHEAIndex >= mHEAs.size()) mHEAIndex = 0;
            DeviceCategory hea = mHEAs.get(mHEAIndex);
            hea.setChecked(true);
            if (!mainActivity.isShowAllLight) {
                AppManager.getInstance(getContext()).mSelectDeviceCategory = hea;
            }
            mHEAadapter.notifyDataSetChanged();
        }
    }


    private void initGroupRecycleView() {
        Context context = getContext().getApplicationContext();
        mGroupAdapter = new MainGroupAdapter(context);
        mRecyclerViewGroup.setAdapter(mGroupAdapter);
        mGroupLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
        mRecyclerViewGroup.setLayoutManager(mGroupLayoutManager);

        mGroupAdapter.setOnItemClickListener(position -> {
            mGroupIndex = position;
            AppManager.getInstance(getContext()).mGroupIndex = position;
            setCurrGroup();
        });
        mGroupAdapter.setItemPowerCallBack(new MainGroupAdapter.ItemPowerCallBack() {
            @Override
            public void notifyPower(int position, String cmd) {
                mGroupIndex = position;
                AppManager.getInstance(getContext()).mGroupIndex = position;
                setCurrGroup();
                DeviceCategory group = mGroupAdapter.getItem(mGroupIndex);
                if (group.getCategory() == 1) {
                    AppManager.getInstance(getContext()).onOrOff(group.getGroupId(), cmd);
                }
            }

            @Override
            public void notifyPage(int position) {
                gotoGroupFragment(position);
            }
        });

    }

    private void gotoGroupFragment(int position) {
        List<DeviceCategory> allData = mGroupAdapter.getAllData();
        if (allData == null || allData.size() <= position) {
            return;
        }//防止数组越界
        mGroupIndex = position;
        AppManager.getInstance(getContext()).mGroupIndex = position;
        setCurrGroup();
        DeviceCategory mainItem = mGroupAdapter.getItem(mGroupIndex);
        if (mainItem.getFamilyId().equalsIgnoreCase("12345678")) {
            BallLight defaultGroup = AppManager.getInstance(getContext()).mDefaultBallLight;
            AppManager.getInstance(getContext()).selectGroup = defaultGroup;
            GroupFragment fragment = new GroupFragment();
            fragment.mGroup = defaultGroup;
            start(fragment);
        } else {
            BallLightDao ballLightDao = new BallLightDao(getContext());
            BallLight ballLight = ballLightDao.getByUuid(mainItem.getUuid());
            AppManager.getInstance(getContext()).selectGroup = ballLight;
            GroupFragment fragment = new GroupFragment();
            fragment.mGroup = ballLight;
            start(fragment);
        }

    }


    private void gotoAllGroupFragment() {
        if (mSelectedFamily == null) return;
       /* if (AppManager.getInstance(getContext()).mAllGroup ==null || !AppManager.getInstance(getContext()).mAllGroup.getFamilyId(). equals(mSelectedFamily.getFamilyId())
                || !AppManager.getInstance(getContext()).mAllGroup.getGroupId().equals("00")  ) {
        }*/
        AppManager.getInstance(getContext()).isControlAll = true;
        GroupFragment fragment = new GroupFragment();
        fragment.mGroup = AppManager.getInstance(getContext()).mAllGroup;
        start(fragment);
//        start(GroupFragment.newInstance(AppManager.getInstance(getContext()).mAllGroup));
    }


    private void initSceneRecycleView() {
        Context context = getContext();
        mHEAadapter = new MainHEAAdapter(context);
        mRecyclerViewScene.setAdapter(mHEAadapter);
        mSceneLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
        mRecyclerViewScene.setLayoutManager(mSceneLayoutManager);

        mHEAadapter.setOnItemClickListener(position -> {
            mHEAIndex = position;
            AppManager.getInstance(getContext()).mHEAIndex = position;
            setCurrHEA();
        });

        mHEAadapter.setItemPowerCallBack(new MainHEAAdapter.ItemPowerCallBack() {
            @Override
            public void notifyPower(int position, String cmd) {
                mHEAIndex = position;
                AppManager.getInstance(getContext()).mHEAIndex = position;
                setCurrHEA();
                DeviceCategory group = mHEAadapter.getItem(position);
                if (group.getCategory() == 2) {
                    if (group.getModel().equals("02040001")) {
                        boolean isOn = SPUtil.getBool(Constants.ISONSIXFAN, false);//风扇的状态，默认是没开
                        if (isOn) {
                            AppManager.getInstance(getContext()).commandAdvertise("01", group.getFamilyId(), group.getGroupId(), "01000000", "000000", mSelectedFamily.getSeed(), mSelectedFamily.getFeedback(), 1, "7202");
                            isOn = false;
                        } else {
                            AppManager.getInstance(mainActivity).commandAdvertise("01", group.getFamilyId(), group.getGroupId(), "05000000", "000000", mSelectedFamily.getSeed(), mSelectedFamily.getFeedback(), 1, "7202");
                            isOn = true;
                        }

                        SPUtil.put(Constants.ISONSIXFAN, isOn);
                    } else {
                        AppManager.getInstance(getContext()).commandAdvertise("01", group.getFamilyId(), group.getGroupId(), "01000000", "000000", mSelectedFamily.getSeed(), mSelectedFamily.getFeedback(), 1, "7202");

                    }

                } else if (group.getCategory() == 3) {
                    if (group.getModel().equals("03020001")) {
                        boolean isOn = SPUtil.getBool(Constants.ISONDATAFANLAMP, false);//风扇灯的状态，默认是没开
                        if (isOn) {
                            AppManager.getInstance(getContext()).commandAdvertise("04", group.getFamilyId(), group.getGroupId(), "00000000", "000000", mSelectedFamily.getSeed(), mSelectedFamily.getFeedback(), 1, "7203");
                            isOn = false;
                        } else {
                            AppManager.getInstance(getContext()).commandAdvertise("04", group.getFamilyId(), group.getGroupId(), "00000000", "000001", mSelectedFamily.getSeed(), mSelectedFamily.getFeedback(), 1, "7203");
                            isOn = true;
                        }
                        SPUtil.put(Constants.ISONDATAFANLAMP, isOn);

                    } else {
                        AppManager.getInstance(getContext()).commandAdvertise("01", group.getFamilyId(), group.getGroupId(), "01000000", "000000", mSelectedFamily.getSeed(), mSelectedFamily.getFeedback(), 1, "7203");

                    }

                } else if (group.getCategory() == 4) {
                    AppManager.getInstance(getContext()).commandAdvertise("01", group.getFamilyId(), group.getGroupId(), "01000000", "000000", mSelectedFamily.getSeed(), mSelectedFamily.getFeedback(), 1, "7204");

                } else if (group.getCategory() == 5) {
                    if (group.getModel().equals("05020001")) {
                        boolean isOn = SPUtil.getBool(Constants.ISONNEWBATHHEATERLIGHT, false);
                        if (isOn) {//如果开了就发关
                            AppManager.getInstance(mainActivity).commandAdvertise("01", group.getFamilyId(), group.getGroupId(), "02000000", "000000", mCurrFamily.getSeed(), mCurrFamily.getFeedback(), 1, "7205");
                            isOn = false;

                        } else {
                            AppManager.getInstance(mainActivity).commandAdvertise("01", group.getFamilyId(), group.getGroupId(), "02010000", "000000", mCurrFamily.getSeed(), mCurrFamily.getFeedback(), 1, "7205");
                            isOn = true;

                        }
                        SPUtil.put(Constants.ISONNEWBATHHEATERLIGHT, isOn);
                    } else {
                        AppManager.getInstance(getContext()).commandAdvertise("01", group.getFamilyId(), group.getGroupId(), "01000000", "000000", mSelectedFamily.getSeed(), mSelectedFamily.getFeedback(), 1, "7205");

                    }

               /* }else if (group.getCategory() == 6) {
                    mAppManager.commandAdvertise("01",group.getFamilyId(),group.getGroupId(),"01000000","000000",mSelectedFamily.getSeed(),mSelectedFamily.getFeedback(),1,"7206");
                }else if (group.getCategory() == 7) {
                    mAppManager.commandAdvertise("01",group.getFamilyId(),group.getGroupId(),"01000000","000000",mSelectedFamily.getSeed(),mSelectedFamily.getFeedback(),1,"7207");
                }else if (group.getCategory() == 8) {
                    mAppManager.commandAdvertise("01",group.getFamilyId(),group.getGroupId(),"01000000","000000",mSelectedFamily.getSeed(),mSelectedFamily.getFeedback(),1,"7208");*/
                } else if (group.getCategory() == 9) {
                    AppManager.getInstance(getContext()).commandAdvertise("01", group.getFamilyId(), group.getGroupId(), "01000000", "000000", mSelectedFamily.getSeed(), mSelectedFamily.getFeedback(), 1, "7209");
                } else if (group.getCategory() == 13) {
                    int key = 0;
                    boolean isOnHumidifier = SPUtil.getBool(Constants.ISONHUMIDIFIER, true);
                    if (isOnHumidifier) {
                        key = 0x41;
                    } else {
                        key = 0x42;
                    }
                    int fkey = (key ^ 0xff);
                    String keyHex = getByteHex(key) + getByteHex(fkey);
                    AppManager.getInstance(mainActivity).commandAdvertise("02", group.getFamilyId(), group.getGroupId(), "137F" + keyHex, "000000", mCurrFamily.getSeed(), mCurrFamily.getFeedback(), 1, "720D");
                    SPUtil.put(Constants.ISONHUMIDIFIER, !isOnHumidifier);
                }/*else if (group.getCategory() == 11) {
                    mAppManager.commandAdvertise("02",group.getFamilyId(),group.getGroupId(),"00000000",cmd,mSelectedFamily.getSeed(),mSelectedFamily.getFeedback(),1,"720B");

                }*/

            }

            @Override
            public void notifyPage(int position) {
                gotoHEAFragment(position);
            }
        });

    }


    private void gotoHEAFragment(int position) {
        List<DeviceCategory> allData = mHEAadapter.getAllData();
        if (allData == null || allData.size() <= position) {
            return;
        }//防止数组越界

        mHEAIndex = position;
        AppManager.getInstance(getContext()).mHEAIndex = position;
        setCurrHEA();
        DeviceCategory mainItem = mHEAadapter.getItem(position);
        if (mainItem.getModel().equals("02010001")) {//跳转到标准风扇界面
            start(FanFragment.newInstance(mainItem));

        } else if (mainItem.getModel().equals("03010001")) {//跳转到标准风扇灯界面
            start(FanLampFragment.newInstance(mainItem));

        } else if (mainItem.getModel().equals("04010001")) {//跳转到标准的电暖器界面
            start(ElectricHeaterFragment.newInstance(mainItem));

        } else if (mainItem.getModel().equals("05010001")) {//跳转到标准浴霸界面
            start(BathHeaterFragment.newInstance(mainItem));

        } else if (mainItem.getModel().equals("06010001")) {//跳转到标准窗帘界面
            start(CurtainFragment.newInstance(mainItem));

        } else if (mainItem.getModel().equals("07010001")) {//跳转到标准的晾衣架界面
            start(ClotheshorseFragment.newInstance(mainItem));

        } else if (mainItem.getModel().equals("08010001")) {//跳转到标准的空调界面
            start(AirConditioningFragment.newInstance(mainItem));

        } else if (mainItem.getModel().equals("09010001")) {//跳转到标准的养生盆界面
            start(HealthBasinFragment.newInstance(mainItem));

        } else if (mainItem.getModel().equals("0D010001")) {//跳转到标准的加湿器界面
            start(HumidifierFragment.newInstance(mainItem));

        } else if (mainItem.getModel().equals("03020001")) {//跳转到发送数据的风扇灯界面
//             start(DataFanLampFragment.newInstance(mainItem));
            start(NewDataFanLampFragment.newInstance(mainItem));

        } else if (mainItem.getModel().equals("02040001")) {//跳转到6个按键的风扇界面
            start(SixFanFragment.newInstance(mainItem));

        } else if (mainItem.getModel().equals("05020001")) {//跳转到新的浴霸界面
            start(NewBathHeaterFragment.newInstance(mainItem));
        } else if (mainItem.getModel().equals("0B010001")) {//跳转到智能开关
            start(SmartSwitchFragment.newInstance(mainItem));
        }


        /* if (mainItem.getCategory() == 2) {

            start(FanFragment.newInstance(mainItem));

        } else if (mainItem.getCategory() == 3) {
             Log.e("LFX", "FanLampFragment==" + mainItem.toString());
            start(FanLampFragment.newInstance(mainItem));

        } else if (mainItem.getCategory() == 4) {

            start(ElectricHeaterFragment.newInstance(mainItem));

        } else if (mainItem.getCategory() == 5) {

            start(BathHeaterFragment.newInstance(mainItem));

        } else if (mainItem.getCategory() == 6) {

            start(CurtainFragment.newInstance(mainItem));

        } else if (mainItem.getCategory() == 7) {

            start(ClotheshorseFragment.newInstance(mainItem));

        }else if (mainItem.getCategory() == 8) {

            start(AirConditioningFragment.newInstance(mainItem));

        }else if (mainItem.getCategory() == 9) {

            start(HealthBasinFragment.newInstance(mainItem));

        }*/
    }


    @OnClick({R.id.btn_help, R.id.btn_mike, R.id.btn_scan,
            R.id.btn_add, R.id.btn_lighting, R.id.btn_hea, R.id.btn_setup,
            R.id.btn_on, R.id.btn_off, R.id.btn_oper, R.id.btn_add_hea})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_help:
                if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
                    return;
                }
                lastClickTime = System.currentTimeMillis();

                start(HelpFragment.newInstance());
//                start(HumidifierFragment.newInstance());
                break;

            case R.id.btn_mike:
                setMikeStatus();
                break;

            case R.id.btn_scan:
                setScanStatus();
                break;

            case R.id.btn_add:
                /*if (mainActivity.isShowAllLight) {
                    start(CreateGroupFramgment.newInstance(mSelectedFamily));
                }else {
                    start(ScanHEAFramgment.newInstance(mSelectedFamily));
                }*/

//                start(CreateSceneFragment.newInstance());
                break;

            case R.id.btn_lighting:
                mainActivity.isShowAllLight = true;
                int count = mGroupAdapter.getCount();
                if (count != 0) {
                    DeviceCategory ballLight = mGroupAdapter.getItem(mGroupIndex);
                    ballLight.setChecked(true);
                    if (ballLight != null) {
                        AppManager.getInstance(getContext()).mSelectDeviceCategory = ballLight;
                    }
                }

                showGroup(true);
                break;
            case R.id.btn_hea:
                mainActivity.isShowAllLight = false;
                int count1 = mHEAadapter.getCount();
                if (count1 != 0) {
                    DeviceCategory hea = mHEAadapter.getItem(mHEAIndex);
                    if (hea != null) {
                        hea.setChecked(true);
                        AppManager.getInstance(getContext()).mSelectDeviceCategory = hea;
                    }

                }


                showGroup(false);
                break;
            case R.id.btn_setup:
                if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
                    return;
                }
                lastClickTime = System.currentTimeMillis();

                start(SettingFragment.newInstance());

                break;

            case R.id.btn_on:
                AppManager.getInstance(getContext()).allPower("00", "000100");
                break;

            case R.id.btn_off:
                AppManager.getInstance(getContext()).allPower("00", "000000");
                break;

            case R.id.btn_oper:
                if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
                    return;
                }
                lastClickTime = System.currentTimeMillis();
                gotoAllGroupFragment();
                break;

            case R.id.btn_add_hea:
                if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
                    return;
                }
                lastClickTime = System.currentTimeMillis();
                start(ScanHEAFramgment.newInstance(mSelectedFamily));
                break;
        }
    }


    /**
     * 显示不同界面
     *
     * @param isGroup
     */
    private void showGroup(boolean isGroup) {
        mainActivity.isShowAllLight = isGroup;
        mRecyclerViewGroup.setVisibility(isGroup ? View.VISIBLE : View.GONE);

        if (LocaleUtil.getLanguage().startsWith("zh")) {
//            mBtnMike.setVisibility(isGroup ? View.VISIBLE: View.GONE);
            mBtnMike.setVisibility(View.VISIBLE);
        } else {
            mBtnMike.setVisibility(View.GONE);
        }

        mLlListMain.setVisibility(isGroup ? View.VISIBLE : View.GONE);
//        mBtnScan.setVisibility(isGroup ? View.VISIBLE: View.GONE);
//        mBtnHelp.setVisibility(isGroup ? View.VISIBLE : View.GONE);
        mBtnScan.setVisibility(View.VISIBLE);
        mBtnHelp.setVisibility(View.VISIBLE);
//        mBtnAdd.setVisibility(View.VISIBLE);
        if (mSelectedFamily != null) {
            if (mSelectedFamily.getType() == 0) {
                mBtnAddHea.setVisibility(View.INVISIBLE);
            } else {
                mBtnAddHea.setVisibility(View.VISIBLE);
            }
        }

        mRecyclerViewScene.setVisibility(isGroup ? View.GONE : View.VISIBLE);
        mRlHeaList.setVisibility(isGroup ? View.GONE : View.VISIBLE);
//        mBtnAdd.setVisibility(isGroup ? View.GONE : View.VISIBLE);
        mBtnLighting.setSelected(isGroup);
        mBtnHea.setSelected(!isGroup);
    }

    private void setMikeStatus() {
        boolean b = false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            b = HiPermission.checkPermission(mainActivity, Manifest.permission.RECORD_AUDIO);
        } else {
            b = PermissionChecker.checkSelfPermission(mainActivity, Manifest.permission.RECORD_AUDIO) == PermissionChecker.PERMISSION_GRANTED;
        }

        if (b) {

            boolean selected = !mBtnMike.isSelected();
            if (selected) {
                showPopupWindow(mBtnMike, R.drawable.voice_command);
                Intent intent = new Intent(mainActivity, BDService.class);
                intent.putExtra("service_cmd", "startSpeech");
                getContext().startService(intent);
            } else {
                Intent intent = new Intent(mainActivity, BDService.class);
                intent.setAction("stop service");
                mainActivity.stopService(intent);
            }

            mBtnMike.setSelected(selected);
            setSpeechEnable(selected);
            EventBus.getDefault().post(new MyEvent(Constants.SPEECH_ENABLE, selected));
            mainActivity.isPermission = false;

        } else {
            confirType = 2;
            showConfirmDialog(getString(R.string.open_recording_permission));
        }

    }

    private void refreshData() {
        showGroup(mainActivity.isShowAllLight);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleEvent(MyEvent event) {
        String tag = event.getTag();
        Object data = event.getData();
        switch (tag) {
            case Constants.SPEECH_ENABLE:
                if ((boolean) data) {
                    mBtnMike.setSelected(true);
                } else {
                    mBtnMike.setSelected(false);
                }
                break;

            case Constants.SELECTGROUP:
                DeviceCategory group = (DeviceCategory) data;
                if (group.getCategory() == 1) {
                    updateGroupStatus(group);
                } else {
                    updateHEAStatus(group);
                }

                break;


        }

    }

    @Override
    protected void confirmOperation() {
        super.confirmOperation();
        if (confirType == 2) {
            Intent localIntent = new Intent();
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= 9) {
                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                localIntent.setData(Uri.fromParts("package", mainActivity.getPackageName(), null));
            } else if (Build.VERSION.SDK_INT <= 8) {
                localIntent.setAction(Intent.ACTION_VIEW);
                localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                localIntent.putExtra("com.android.settings.ApplicationPkgName", mainActivity.getPackageName());
            }
            mainActivity.isPermission = true;
            startActivity(localIntent);
        }


        if (confirType == 1) {
            Intent localIntent = new Intent();
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= 9) {
                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                localIntent.setData(Uri.fromParts("package", mainActivity.getPackageName(), null));
            } else if (Build.VERSION.SDK_INT <= 8) {
                localIntent.setAction(Intent.ACTION_VIEW);
                localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                localIntent.putExtra("com.android.settings.ApplicationPkgName", mainActivity.getPackageName());
            }
            startActivity(localIntent);
            mHaveCameraPermission = true;
        }

    }


    private void setScanStatus() {
        boolean b = false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            b = HiPermission.checkPermission(getActivity(), Manifest.permission.CAMERA);

        } else {
            b = PermissionChecker.checkSelfPermission(mainActivity, Manifest.permission.CAMERA)
                    == PermissionChecker.PERMISSION_GRANTED;
        }

        if (b) {
            startActivityForResult(new Intent(getActivity(), CaptureActivity.class), 1000);
        } else {
            showConfirmDialog(getString(R.string.open_camera_permission));
            confirType = 1;
        }
    }


    public static ISupportFragment newInstance() {
        return new MainFragment();
    }


    @Override
    public boolean onBackPressedSupport() {
        showExitDialog(getContext());
        return true;
    }


    public void showExitDialog(Context context) {
        CustomDialog.Builder builder = new CustomDialog.Builder(context);
        builder.setMessage(getString(R.string.is_exit));
        builder.setMessageSize(20);
        builder.setTitle(getString(R.string.tips));
        builder.setPositiveButton(getString(R.string.btn_confirm), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                SPUtil.put(Constants.ISDOWNLOAD, false);

                Intent intent = new Intent(mainActivity, BaiDuService.class);
                intent.setAction("stop service");
                mainActivity.stopService(intent);

                _mActivity.finish();
//                Process.killProcess(Process.myPid());
//                System.exit(0);
            }
        });


        builder.setNegativeButton(getString(R.string.btn_cancel), new android.content.DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        CustomDialog customDialog = builder.create();
        customDialog.show();
    }


}
